package com.gang.lingdian.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;


class MyTask extends RecursiveTask<Integer> {

    //拆分差值不能大于10，计算10以内的加法
    private final Integer VALUE = 10;

    //开始值
    private int begin;
    //结果值
    private int end;
    //计算结果
    private int result;

    public MyTask(int begin,int end){
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        //判断两数值是否大于10
        if(end-begin<=VALUE){
            // 计算结果
            for (int i = begin; i <= end; i++) {
                result = result +i;
            }
        } else {
            // 进一步切分
            int middle = (end + begin) / 2;
            // 拆分左边
            MyTask myTask = new MyTask(begin,middle);
            // 拆分右边
            MyTask myTask1 = new MyTask(middle+1,end);
            // 调用方法拆分
            myTask.fork();
            myTask1.fork();
            // 合并计算
            result = myTask.join() + myTask1.join();
        }
        return result;
    }
}
public class ForkJoinDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //创建Mytask对象
        MyTask myTask = new MyTask(0,100);
        // 创建分支合并队形
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
        Integer integer = forkJoinTask.get();
        System.out.println(integer);
        // 关闭
        forkJoinPool.shutdown();

    }

}
